// 购买后的课时 主页面
import React from 'react';
import {
    StyleSheet,
    View,
    Image,
    ScrollView,
    RefreshControl,
    Text,
    TouchableOpacity
} from 'react-native';
import Tab from '../../component/Tab'
import Loading from '../../common/Loading'
import { pageMyOrder } from '../../api/my'
import NavigatorBar from '../../common/NavigationBar';
import BottomBarLimit from '../../common/BottomBarLimit';
import {setSpText,setHW} from '../../component/ScreenUtil'
//获取设备的宽度和高度
const Dimensions = require('Dimensions');
const { height,width } = Dimensions.get('window');
const cacheData = {
	total: 0,
	items: [],
	nextPage: 1
}

import BaseBridge from '../../common/Native/BaseBridge';

export default class MyOrder extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            tabName:'AllOrder',//默认
            tabList: [
                {
                    tabText: '全部',
                    tabName: 'AllOrder',
                },
                {
                    tabText: '已支付',
                    tabName: 'HadBuy',
                },
                {
                    tabText: '待支付',
                    tabName: 'NoBuy',
                }
            ],
            dataList: [],//所有订单
            isRefreshing: false,
			moreData: false,
			isLoading: false
        }
    }
    componentWillReceiveProps(curProps) {
        this.setState({dataList:[]})
        this._fetchData()
    }
    // 获取我的订单
    componentDidMount() {
        this.setState({dataList:[]})
        this._fetchData()
    }
    // 获取数据
    _fetchData(tabName) {
        let json = {
            "PAGE": cacheData.nextPage,
            "ROWS": 10,
            "PAY_USER_ID": global.ECourseConstant.userInfo.uuid,
            "STATUS": ""
        }
        switch(tabName){
            case 'AllOrder':
                this._pageMyOrder(json)
                break;
            case 'HadBuy':
                json.STATUS='2'
                this._hadBuyList(json)
                break;
            case 'NoBuy':
                json.STATUS='1'
                this._noBuyList(json)
                break;
            default:
                this._pageMyOrder(json)
        }
    }
    // 组件销毁执行
    componentWillUnmount() {
        this.cancelData()//清空数据
    }
    _pageMyOrder(json) {
        pageMyOrder(json).then(res => {
            global.log(res,'res----------------')
            cacheData.total == 0 && this.setState({ loading: false });
            cacheData.items = this.state.dataList.concat(res.LIST);
            var data = [...cacheData.items];
            cacheData.total = res.PAGINATION.TOTAL;
            this.setState({ dataList: [], isRefreshing: false });
        })
    }
    _noBuyList(json) {
        pageMyOrder(json).then(res => {
            global.log(res,'res------')
            cacheData.total == 0 && this.setState({ loading: false });
            cacheData.items = this.state.dataList.concat(res.LIST);
            cacheData.total = res.PAGINATION.TOTAL;
            var data = [...cacheData.items];
            this.setState({ dataList: data, isRefreshing: false });
        })
    }
    _hadBuyList(json) {
        pageMyOrder(json).then(res => {
            cacheData.total == 0 && this.setState({ loading: false });
            cacheData.items = this.state.dataList.concat(res.LIST);
            cacheData.total = res.PAGINATION.TOTAL;
            var data = [...cacheData.items];
            this.setState({ dataList: data, isRefreshing: false });
        })
    }
    //  刷新数据
    seachData(tabName) {
        this.cancelData()//清空数据
        this._fetchData(tabName)
    }
    loading(flag) {
        return (
           this.setState({ loading: flag })
        )
    }
    goBack() {
        BaseBridge.backToExue();
    }
    // 渲染按钮 返回按钮
    renderLeftButton(image) {
        var that=this;
        return <TouchableOpacity
            style={{ padding: 8 }}
            onPress={() => {
                if (global.ECourseConstant.eCourseFirstRouter=="MyOrder") {
                     that.goBack();
                } else {
                    this.props.navigation.goBack();
                }
            }}>
            <Image style={{ width: 34, height: 34 }} source={image} />
        </TouchableOpacity>;
    }
    // 刷新首页
	_onRefresh = () => {
        this.cancelData();
        this.setState({
            isRefreshing: true
        })
        this._fetchData(this.state.tabName)
    }
    
    // 切换tab时
    getTabName(tabName){
        this.setState({loading:true,tabName:tabName})
        this.cancelData()//清空数据
        this._fetchData(tabName);//重新刷新
    }
    render() {
        return (
            <View>
                <NavigatorBar title={'我的订单'} leftButton={this.renderLeftButton(require('../../assets/imgs/back.png'))}/>
                <ScrollView
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this._onRefresh.bind(this)}
                            tintColor="#FF8A00"
                            // title="加载中..."
                            titleColor="#ddd"
                            colors={['#FF8A00']}
                            progressBackgroundColor="#ffffff"
                        />
                    }
                    showsVerticalScrollIndicator={false}
                    onScroll={this._onScroll.bind(this)}
                    scrollEventThrottle={20}>
                    <View style={styles.MyCare}>
                        <Tab tabList={this.state.tabList}
                             ResetSearch={()=>this._onRefresh()}
                             allOrderList={this.state.dataList}
                             seachData={(tabName) => this.seachData(tabName)}
                             tellParentTabName={(tabName)=>this.getTabName(tabName)}
                             currentTabName={this.state.tabName}
                            {...this.props}>
                        </Tab>
                        {this.loadMore()}
                        {this.loading()}
                        {this.NoData()}
                    </View>
                    <BottomBarLimit/>
                </ScrollView>
            </View>
        );
    }
   
    // 加载更多数据
	_onScroll = (event) => {
		if (this.state.isLoading || !this.hasMoreList()) {
			return;
		}
		let y = event.nativeEvent.contentOffset.y;
		let height = event.nativeEvent.layoutMeasurement.height;
		let contentHeight = event.nativeEvent.contentSize.height;
		if (y + height >= contentHeight - 20) {
			this.setState({
				loadMore: true,
				isLoading: false
			}, () => {
				cacheData.nextPage = cacheData.nextPage + 1;
                this._fetchData(this.state.tabName)
			});

		}
    }
    hasMoreList() {
		if (this.state.dataList.length == cacheData.total && cacheData.total > 0) {
			this.setState({
				moreData: false
			})
			return false
		}
		return true
    }
    // 清空数据
    cancelData(){
        cacheData = {
			items: [],
			nextPage: 1,
			total: 0
        }
        this.setState({
            dataList: [],//所有订单
            isLoading: false,
            moreData: false
        })
    }
    // 加载loading
	loading(){
		if(this.state.loading){
			return(
				<View style={{height:height - 100}}>
					<Loading/>
				</View>
			)
		}
	}
	// 正在加载or底部
	loadMore(){
        if(this.state.dataList.length>10){
            if(!this.state.loading){
                if(this.state.moreData){
                    return(
                        <View style={styles.loadMore}>
                            <Text style={styles.loadMoreText}>正在加载中...</Text>
                        </View>
                    )
                }else{
                    return(
                        <View style={styles.loadMore}>
                            <Text style={styles.loadMoreText}>已经全部加载完毕</Text>
                        </View>
                    )
                }
            }
        }
	}
	// 没有数据
	NoData(){
		if(!this.state.loading&&!this.state.moreData&&!this.state.dataList.length){
			return(
				<Text style={styles.empty}>暂无数据</Text>
			)
		}
	}
}
// console.log(setHW(44),'setHW')
const styles = StyleSheet.create({
    MyCare: {
        backgroundColor: '#F7F7F9',
    },
    empty: {
        backgroundColor: '#fff',
        textAlign: 'center',
        height: height - setHW(100),
        lineHeight: setHW(400),
        color: '#666',
        fontSize:setSpText(26),
        width: width,
    },
	loadMore: {
		flexDirection: 'row',
		justifyContent: 'center',
		height: setHW(100),
		alignItems: 'center',
	},
	loadMoreText: {
		color: '#ddd',
	}
})